//入口文件
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

//导入格式化时间的插件
import moment from 'moment'
//定义全局的过滤器
Vue.filter('dateFormat',function(dataStr,pattern = "YYYY-MM-DD HH:MM:SS"){
	return moment(dataStr).format(pattern)
})

//导入vue-resource包
import VueResource from 'vue-resource'
Vue.use(VueResource)

//设置AJAX根路径
Vue.http.options.root='https://locally.uieee.com./categories';
//设置请求头
Vue.http.options.emulateJSON = true;

//导入路由实例
import router from './router.js'

//按需导入mint-ui
import {Header,Swipe,SwipeItem,Button,Lazyload,Switch} from 'mint-ui'
Vue.component(Header.name,Header)
Vue.component(Swipe.name, Swipe);
Vue.component(SwipeItem.name, SwipeItem);
Vue.component(Button.name, Button);
Vue.component(Switch.name, Switch);
Vue.use(Lazyload);
//导入MUI的样式
import './lib/mui/css/mui.css'
import './lib/mui/css/icons-extra.css'

// 导入vue-preview插件
import VuePreview from 'vue-preview'
Vue.use(VuePreview)

import app from './app.vue'

//引入vuex
import Vuex from 'vuex'
Vue.use(Vuex)

//初始化页面的时候 从localStrage中获取 购物车信息
var car = JSON.parse(localStorage.getItem("car") || "[]");


//用Vuex生成 公共数据对象store
var store = new Vuex.Store({
	state:{//this.$store.state.count
		id:1,
		car:car
	},
	mutations:{//this.$store.commit("方法名",方法的第二个参数)

		//增加商品
		addToCar(state,goodsinfo){
			var flag = false;
			state.car.some((item)=>{
				if(item.id == goodsinfo.id){
					item.count = parseInt(item.count)+parseInt(goodsinfo.count);
					flag=true
					return true
				}
			})
			if(!flag){
				state.car.push(goodsinfo);
			}
			//购物车数据同步更新到localstorage中 
			localStorage.setItem("car",JSON.stringify(state.car));
		},

		//更新商品信息
		updateToCar(state,goodsinfo){

			state.car.some((item)=>{
				if(item.id == goodsinfo.id){
					item.count = parseInt(goodsinfo.count);
					item.selected = goodsinfo.selected;
					return true
				}
			})
			//购物车数据同步更新到localstorage中 
			localStorage.setItem("car",JSON.stringify(state.car));
		},
		deleteShop(state,id){
			var index = 0;
				state.car.some((item,i)=>{
					if(item.id == id){
						index = i;
						return true
					}
				})
				state.car.splice(index,index+1);
				localStorage.setItem("car",JSON.stringify(state.car))
		},

	},
	getters:{
		getAllCount(state){//this.$store.getters.方法名
			var total = 0;
			state.car.forEach((item)=>{
				total += parseInt(item.count);
			})
			return total
		},
		getNumObj(state){
			var o = {};
			state.car.forEach((item)=>{
				o[item.id] = item.count
			})
			return o 
		},
		getSelectObj(state){
			var o = {};
			state.car.forEach((item)=>{
				o[item.id] = item.selected
			})
			return o
		},
		getGoodsCountAndAmount(state){
			var o = {
				count:0,
				amount:0
			}
			state.car.forEach((item)=>{
				if(item.selected){
					o.count+=item.count;
					o.amount+=item.count*2199;
				}
			})
			return o
		}
	},
	
});

var vm = new Vue({
	el:'#app',
	render:(c)=>c(app),
	router,
	store,
})